import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/login/page/login_page.dart';
import 'package:ls_work/login/page/update_password_page.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/sql/AppDbUtils.dart';
import 'package:ls_work/ui/patrol/offline_task_record_page.dart';
import 'package:ls_work/util/native_toast.dart';
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/viewmodel/new_yyt_view_model.dart';
import 'package:ls_work/widgets/load_image.dart';

import '../login/page/reset_password_page.dart';

class NewYytPage extends BaseStatefulMvvmWidget {
  @override
  State<StatefulWidget> createState() => _NewYytState();
}

class _NewYytState extends BaseMvvmState<NewYytViewModel, NewYytPage> with AutomaticKeepAliveClientMixin{

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((duration){
      if(UserManager.lastUpdatePwdTime.isNullOrEmpty()){
        showChangePasswordDialog();
      }
    });
  }

  void showChangePasswordDialog(){
    showDialog(context: context, builder: (context){
      return PopScope(child: CupertinoAlertDialog(
        title: Text("修改密码"),
        content: Text("首次登录，请修改密码"),
        actions: [
          Row(
            children: [
              TextButton(onPressed: (){
                UserManager.instance.logout();
                Go().pushRemoveUntil(LoginPage());
              }, child: Text("退出登录")).setWeight(1),

              SizedBox(width: 12,),

              TextButton(onPressed: (){
                // Navigator.of(context).pop();
                Go().push(ResetPasswordPage());
              }, child: Text("去修改")).setWeight(1)
            ],
          )
        ],
      ),canPop: false,);
    },barrierDismissible: false);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return initProvider();
  }

  @override
  Widget buildLoadingContentView() {
    return ListView(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            if(!GlobalConfigs.homeLogo.isNullOrEmpty())
            LoadAssetImage(
              GlobalConfigs.homeLogo!,
              width: 45,
              fit: BoxFit.cover,
            ).onTap(() {
              viewModel.clickToShowHealth();
            }),
            SizedBox(
              width: 30,
            ),
            Expanded(
              child: Text(
                '“  嗨，${SpUtil.getString(
                    Constant.userName)}，早上好，\n感谢您对每一位长者的付出！”',
                style: TextStyles.home_tips,
              ),
            )
          ],
        ).addToContainer(
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16)),

        if(!RequestUrlUtils.code.contains("dj"))
          ImageLoad(
            formatImage("image_home_banner", parentPath: "assets"),
            width: double.infinity,
            height: 100,
            fit: BoxFit.cover,
            isAsset: true,
          ).toRound(borderRadius: BorderRadius.circular(8)).addToContainer(
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10)),

        if(viewModel.localPatrolRecordNum > 0)
          Row(
            children: [
              CommonText(
                  '当前有${viewModel.localPatrolRecordNum}条本地巡防记录待上传',textColor: Colors.white)
                  .setWeight(1),
              TextButton(onPressed: () {
                Go().push(OfflineTaskRecordPage());
              }, child: Text('去上传',style: TextStyle(color: Colors.white,fontSize: 13),),
                style: ButtonStyle(
                    shape: WidgetStateProperty.all(
                        StadiumBorder(side: BorderSide(color: Colors.white))),
                  // backgroundColor: WidgetStateProperty.all(Colors.blue.withOpacity(0.5))
                ),)
            ],
          ).addToContainer(color: Colors.blue.withOpacity(0.4),padding: EdgeInsets.symmetric(horizontal: 16,vertical: 4)),
        // Column(
        //   crossAxisAlignment: CrossAxisAlignment.start,
        //   children: [
        //     CommonText("我的工作",textSize: 18,fontWeight: FontWeight.bold).addToContainer(margin: EdgeInsets.symmetric(vertical: 30,horizontal: 16)),
        //     viewModel.functionWidget()
        //   ],
        // ).addToContainer(color: Colors.white)
        viewModel.contentWidget()
      ],
    );
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("首页"),
        leading: Platform.isIOS ? IconButton(
          icon: Icon(Icons.nfc), onPressed: () {
          viewModel.startNfc();
        },) : null,
        centerTitle: true,
        elevation: 0,
        actions: [

          IconButton(
              onPressed: () async {
                viewModel.scanCode();
              },
              icon: Icon(Icons.qr_code_scanner))
        ],
      ),
      body: loadingContentWidget,
    );
  }

  @override
  NewYytViewModel createViewModel() {
    return NewYytViewModel(context);
  }

  @override
  void onRetryClick() {
  }


  Future<void> initDb() async {
    await AppDbUtils.instance().initDb();
  }


  @override
  void onCreate() {
    super.onCreate();
    initDb();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void onAppShow() {

    super.onAppShow();
    // Future.delayed(Duration(milliseconds: 200), () {
      hideFloatingWidget();
    // });
    // showToast("数字康养已恢复前台运行");
    // NativeUtils.setSecureScreen(false);
  }

  @override
  void onAppHide() {
    showFloatingWidget();
    NativeUtils.showToast("数字康养进入后台运行");
    super.onAppHide();

    // NativeUtils.setSecureScreen(true);

  }

  OverlayEntry? _overlayEntry;

  void showFloatingWidget() {
    _overlayEntry = OverlayEntry(
      builder: (context) => Container(
        color: Colors.grey,
        width: double.infinity,
        height: double.infinity,
      ).onTap((){
        hideFloatingWidget();
      }),
    );

    // 将悬浮窗添加到应用的覆盖层
    Overlay.of(context)!.insert(_overlayEntry!);

  }

  void hideFloatingWidget() {
    // 移除悬浮窗
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

}
